/**
 * 
 */
 package com.webkaifa.utility;
 
 import java.io.PrintWriter;
 import java.io.StringWriter;
import java.nio.ByteBuffer;

 /**
 * @author along
 *
 */
 public class Utils {
	 private static final String NEW_LINE = "\r";
	 public static String getHexDump(byte [] buffer)
	 {
		 return getHexDump(buffer,0);
	 }
	 public static String getHexDump(ByteBuffer byteBuffer)
	 {
		 byteBuffer.mark();
		 int l_nLength=byteBuffer.limit();
		 byte [] buffer =new byte[l_nLength];
		 byteBuffer.get(buffer,0,l_nLength);
		 byteBuffer.reset();
		 if(l_nLength==0)
		 {
			 return "Dump Data Length IS ZERO.";
		 }
		 return getHexDump(buffer,0);
	 }
	 public static String getHexDump(byte [] buffer,int len)
	 {
		 int dataLen=len;
		 if(len<=0||len>buffer.length)
		 dataLen = buffer.length;
		 String dump = "";
		 try 
		 {
		 for (int i=0; i<dataLen; i++) 
		 {
		 if( (i%8) == 0)
		 dump += " "; /* add gap every 8 chars */
		 if( (i%16)==0) 
		 dump += NEW_LINE; 
		 dump += Character.forDigit((buffer[i] >> 4) & 0x0f, 16);
		 dump += Character.forDigit(buffer[i] & 0x0f, 16);
		 dump += " "; 
		 }
		 } catch (Throwable t) {
		 // catch everything as this is for debug
		 dump = "Throwable caught when dumping = " + t;
		 }
		 return dump;
	 }
	 public static String getStackTraceAsString(Throwable e) 
	 {
		 if (e == null)
		 return null; 
		 StringWriter stringWriter = new StringWriter();
		 PrintWriter printWriter = new PrintWriter(stringWriter);
		 e.printStackTrace(printWriter);
		 StringBuffer error = stringWriter.getBuffer();
		 return error.toString();
	} 
 }